package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.xuanzheng.company.entity.AttendanceRecord;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AttendanceRecordService;
import com.xuanzheng.company.service.impl.AttendanceRecordServiceImpl;
import com.xuanzheng.company.entity.CompanyEmployee;
import com.xuanzheng.company.service.CompanyEmployeeService;
import com.xuanzheng.company.service.impl.CompanyEmployeeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 打卡Servlet，处理上班打卡和下班打卡请求
 */
@WebServlet(urlPatterns = {"/api/attendance/checkIn", "/api/attendance/checkOut"})
public class CheckInServlet extends HttpServlet {
    private AttendanceRecordService attendanceRecordService = new AttendanceRecordServiceImpl();
    private CompanyEmployeeService companyEmployeeService = new CompanyEmployeeServiceImpl();
    private Gson gson;
    
    // 初始化Gson，添加Timestamp序列化器
    public CheckInServlet() {
        // 创建一个自定义的Timestamp序列化器
        JsonSerializer<Timestamp> timestampSerializer = new JsonSerializer<Timestamp>() {
            @Override
            public JsonElement serialize(Timestamp timestamp, Type typeOfSrc, JsonSerializationContext context) {
                // 使用SimpleDateFormat格式化时间戳
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return new JsonPrimitive(dateFormat.format(timestamp));
            }
        };
        
        // 使用GsonBuilder注册序列化器
        this.gson = new GsonBuilder()
                .registerTypeAdapter(Timestamp.class, timestampSerializer)
                .create();
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");
        // 添加缓存控制头
        resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Expires", "0");
        
        PrintWriter out = resp.getWriter();
        
        // 获取当前登录用户
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        // 获取操作类型（上班打卡或下班打卡）
        String action = req.getParameter("action");
        System.out.println("打卡操作: " + action + ", 用户: " + user.getName() + " (" + user.getId() + ")");
        
        // 获取用户所在公司信息
        CompanyEmployee employee = companyEmployeeService.getByUserId(user.getId());
        
        if (employee == null) {
            // 用户不属于任何公司
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "您不属于任何公司，无法打卡");
            out.print(gson.toJson(result));
            return;
        }
        
        System.out.println("用户所属公司ID: " + employee.getCompanyId() + ", 员工编号: " + employee.getEmployeeNumber());
        
        Map<String, Object> result;
        
        try {
            if ("checkOut".equals(action)) {
                // 下班打卡
                System.out.println("处理下班打卡请求");
                result = attendanceRecordService.checkOut(user.getId(), employee.getCompanyId());
            } else {
                // 默认为上班打卡
                System.out.println("处理上班打卡请求");
                result = attendanceRecordService.checkIn(user.getId(), employee.getCompanyId(), employee.getEmployeeNumber());
            }
            
            System.out.println("打卡结果: " + (result.get("success").equals(true) ? "成功" : "失败") + 
                    ", 消息: " + result.get("message"));
            
            if (result.get("success").equals(true) && result.get("data") != null) {
                AttendanceRecord record = (AttendanceRecord) result.get("data");
                System.out.println("打卡记录详情: ID=" + record.getId() + 
                    ", 公司ID=" + record.getCompanyId() + 
                    ", 用户ID=" + record.getUserId() + 
                    ", 员工编号=" + record.getEmployeeNumber() + 
                    ", 上班时间=" + record.getCheckInTime() + 
                    ", 下班时间=" + record.getCheckOutTime());
            }
            
            // 输出JSON结果
            out.print(gson.toJson(result));
        } catch (Exception e) {
            System.err.println("打卡处理出错: " + e.getMessage());
            e.printStackTrace();
            
            result = new HashMap<>();
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
            out.print(gson.toJson(result));
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");
        // 添加缓存控制头
        resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Expires", "0");
        
        PrintWriter out = resp.getWriter();
        
        // 获取当前登录用户
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        System.out.println("获取今日打卡记录 - 用户: " + (user != null ? user.getName() + " (" + user.getId() + ")" : "未登录"));
        
        if (user == null) {
            // 用户未登录
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        try {
            // 获取用户今日打卡记录
            AttendanceRecord record = attendanceRecordService.getTodayRecord(user.getId());
            System.out.println("今日打卡记录: " + (record != null ? "找到记录，上班时间: " + record.getCheckInTime() + ", 下班时间: " + record.getCheckOutTime() : "未找到记录"));
            
            // 添加更多调试输出
            if (record != null) {
                if (record.getCheckInTime() != null) {
                    System.out.println("上班打卡时间类型: " + record.getCheckInTime().getClass().getName());
                    System.out.println("上班打卡时间值: " + record.getCheckInTime());
                    System.out.println("上班打卡时间toString(): " + record.getCheckInTime().toString());
                }
                
                if (record.getCheckOutTime() != null) {
                    System.out.println("下班打卡时间类型: " + record.getCheckOutTime().getClass().getName());
                    System.out.println("下班打卡时间值: " + record.getCheckOutTime());
                    System.out.println("下班打卡时间toString(): " + record.getCheckOutTime().toString());
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", record);
            
            // 输出JSON结果
            String jsonResult = gson.toJson(result);
            System.out.println("返回JSON: " + jsonResult);
            out.print(jsonResult);
        } catch (Exception e) {
            System.err.println("获取今日打卡记录出错: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取打卡记录失败，系统错误");
            out.print(gson.toJson(result));
        }
    }
} 